package com.youtills.core.crypto;

import sun.misc.BASE64Encoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by IntelliJ IDEA.
 * User: ravi
 * Date: 8/29/12
 * Time: 6:59 PM
 * To change this template use File | Settings | File Templates.
 */
public class MD5Digest implements IDigest{

    public DigestType getDigestType() {
        return DigestType.MD5;
    }

    private final String salt;
    private final MessageDigest digest;

    private final BASE64Encoder encoder = new BASE64Encoder();

    public MD5Digest() {
        this(null);
    }
    public MD5Digest(String salt) {
        this.salt = salt;
        try {
            this.digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new CryptoException("SHA1 is not supported !!!");
        }
    }

    public synchronized String digest(final String text) {
        byte[] textBytes = salt != null ? (salt + text).getBytes() : text.getBytes();
        return encoder.encode(digest.digest(textBytes));
    }

}
